<!-- 设置页 -->
<template>
	<view class="my-content">
		<view class="u-page">



			<!-- 三个内容 -->
			<!-- <view class="about-me"> -->
			<!-- <view class="sect" style="position: relative;display:flex">
				<u-section :arrow="false" :show-line="false" font-size="30" sub-title=" "
					:title="$t('当前语言')"></u-section>
				<div class="langlist">
					<div class="item" :class="{active:lang==='zh'}" @click="langChange('zh')">中</div>
					<div class="item" :class="{active:lang==='ru'}" @click="langChange('ru')">RU</div>
				</div>
			</view> -->

			<view class="sect" @click="link">
				<u-section :show-line="false" font-size="30" sub-title=" " :title="$t('关于我们')"></u-section>
			</view>

			<view class="sect" @click="inspect">
				<u-section :show-line="false" font-size="30" sub-title=" " :title="$t('检查更新')"></u-section>

			</view>
			<view class="sect" @click="clear">
				<u-section :show-line="false" font-size="30" sub-title=" " :title="$t('清除缓存')"></u-section>
			</view>
			<!-- 假的功能，用于上架，上架后会通过接口隐藏 -->

			<view class="sect" @click="policy">
				<u-section :show-line="false" font-size="30" sub-title=" " :title="$t('用户协议')"></u-section>
			</view>
			<view class="sect" @click="yinsi">
				<u-section :show-line="false" font-size="30" sub-title=" " :title="$t('隐私政策')"></u-section>
			</view>

			<view class="sect" style="position: relative;">
				<u-section :arrow="false" :show-line="false" font-size="30" sub-title=" "
					:title="$t('个性化推荐')"></u-section>
				<switch style="transform:scale(0.7);position: absolute; top: -5px;left: 88%" :checked="isChecked2"
					@change="is_tj_action" />
				<view style="font-size: 22rpx;color:#999999;margin-top: 8px;">{{$t('关闭后仅使用基本功能，无法看到个性化推荐内容')}}</view>
			</view>


			<view class="sect" style="position: relative;">
				<u-section :arrow="false" :show-line="false" font-size="30" sub-title=" "
					:title="$t('定推服务开关')"></u-section>
				<switch disabled="true" style="transform:scale(0.7);position: absolute; top: -18rpx;left: 88%"
					:checked="isChecked" @click="setPermissions_action()" />
				<view
					style="width: 80%;color:#999999;margin-top: 15rpx; margin-bottom: 35rpx; margin-left: 0%;font-size: 24rpx;">
					{{$t('为了您能及时获取重要的消息,建议开启系统通知!')}}
				</view>
			</view>


			<view v-if="plat=='app'" v-show="logOff" class="sect" style="position: relative;">
				<u-section :arrow="false" :show-line="false" font-size="30" sub-title=" "
					:title="$t('麦克风')"></u-section>
				<switch @click="kaiqi()" disabled="true" :custom-style="customStyle" hover-class="none"
					style="transform:scale(0.7);position: absolute; top: -18rpx;left: 88%" :checked="isChecked3" />

				<view v-if="plat=='app'"
					style="width: 80%;color:#999999;margin-top: 15rpx; margin-bottom: 35rpx; margin-left: 0%;font-size: 24rpx;">
					<view>{{$t('请开启您手机的“麦克风”权限')}}：{{$t('当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中')}}</view>
					<view
						style="width:100%;height:30px;line-height: 30px; color: red; text-align: center; font-size: 12px;">
						{{ $t(record_quanxian) }}
					</view>
				</view>
			</view>


			<view v-if="plat=='app'&&platform!='ios'" v-show="logOff" class="sect" style="position: relative;">
				<u-section :arrow="false" :show-line="false" font-size="30" sub-title=" "
					:title="$t('悬浮窗')"></u-section>
				<switch @click="xuanfuchuang_action()" disabled="true" :custom-style="customStyle" hover-class="none"
					style="transform:scale(0.7);position: absolute; top: -18rpx;left: 88%" :checked="isChecked4" />
				<view
					style="width: 80%;color:#999999;margin-top: 15rpx; margin-bottom: 35rpx; margin-left: 0%;font-size: 24rpx;">
					{{$t('为了您能及时获取重要的消息,建议开启悬浮窗、并同时开启后台弹窗通知!')}}
				</view>
			</view>



			<view class="sect" @click="cancel">
				<u-section :show-line="false" font-size="30" sub-title=" " :title="$t('注销账户')"></u-section>
			</view>
			<u-popup v-model="showPopup2">
				<view class="xy-popup">
					<view class="xy-popup-title">{{ $t('隐私政策') }}</view>
					<u-parse :html="xyContent2.content" style="width: 90%;margin-left: 2%;"></u-parse>
					<button @click="guanbi" style="margin-top: 50rpx;width: 80%;">
						{{$t('关闭')}}
					</button>
				</view>
			</u-popup>

			<view style="text-align: center;color:#ddd;font-size: 22rpx;">{{$t('当前版本')}} v{{version}}</view>
			<!-- </view> -->
			<view style="margin-top: 163rpx;">
				<!-- <u-button :custom-style="customStyle" hover-class="none" type="primary" @click="logOut">
					{{ $t('退出登录') }}
				</u-button> -->
				<div class="logout" @click="logOut">
					{{ $t('退出登录') }}
				</div>
			</view>
			<u-mask :show="show" @click="show = false">
				<view class="mask">
					<image mode=""
						src="https://gluz-oss.oss-cn-beijing.aliyuncs.com/uploads/20230803/800594ac20fc3b9658a30cc583c7e528.png">
					</image>
					<view style="text-align: center;word-break: break-all;">{{ version }}</view>
					<view v-if="version>=admin_version" style="text-align: center;word-break: break-all;" @click="tz()">
						{{ $t('暂无新版本') }}
					</view>
					<view v-if="version<admin_version" style="text-align: center;word-break: break-all;color: blue;"
						@click="tz()">{{ $t('您的版本过低 请升级到最新版本') }}</view>
				</view>
			</u-mask>
		</view>
	</view>
</template>

<script>
	// #ifndef MP-WEIXIN
	import TencentCloudChat from '@tencentcloud/chat';
	import * as Push from '@/uni_modules/TencentCloud-Push';
	// 引入setPermissions.js文件
	import {
		setPermissions
	} from '@/common/setPermissions.js';

	import permision from "@/js_sdk/wa-permission/permission.js"

	import {
		logout
	} from '@/utils/im'
	// #endif

	export default {
		data() {
			return {
				version: this.$store.state.version,
				lang: uni.getStorageSync("lang"),
				off: '',
				logOff: false,
				show: false,
				showPopup2: false,
				xyContent2: '',
				is_push: 0,
				isChecked: true,
				isChecked2: true,
				version: '',
				admin_version: '',
				//按钮样式
				customStyle: {
					width: '656rpx',
					height: '63rpx',
					background: 'linear-gradient(110deg, #DD2910 0%, #F79B29 100%)',
					'border-radius': '26rpx',
					'font-size': '28rpx',
					'font-family': ' PingFangSC-Semibold, PingFang SC',
					'font-weight': 600,
					color: '#FFFFFF',
				},

				isChecked3: false,
				isChecked4: false,

				plat: '',
				platform: '',
				record_quanxian: '',
				imTencent: ''
			}
		},
		onLoad() {
			var that = this
			that.$u.api.user.appCheck().then(res => {
				that.off = res.pay1
				that.logOff = res.logOff
				that.admin_version = res.banben

				// #ifdef APP-PLUS
				if (res.logOff) {
					setPermissions();


					const systemInfo = uni.getSystemInfoSync();
					const platform = systemInfo.platform;
					that.platform = platform
					uni.getSystemInfo({
						success: res => {
							if (res.uniPlatform === 'app') {
								that.plat = 'app'
							} else if (res.uniPlatform === 'web') {
								that.plat = 'web'
							} else if (res.uniPlatform === 'mp-weixin') {
								that.plat = 'mp-weixin'
							}
							uni.setStorage({
								key: 'plat',
								data: that.plat
							})
						}
					})


					if (that.platform == 'ios') {
						that.requestIosPermission2('record')
					} else {
						that.requestAndroidPermission('record')
					}

				}
				// #endif
			})

			that.getUserInfo();
			that.version = uni.getStorageSync('version');
		},
		onShow() {
			const systemInfo = uni.getSystemInfoSync();
			const platform = systemInfo.platform;
			const that = this
			that.plat = uni.getStorageSync('plat')
			setTimeout(function() {
				if (that.plat == 'app') {
					var message_permission = uni.getStorageSync('message_permission');
					console.log(message_permission)
					if (message_permission == 1) {
						that.isChecked = true
						that.$u.api.user.is_push({
							'data': 1
						}).then(res => {})
					} else {
						that.isChecked = false
						that.$u.api.user.is_push({
							'data': 2
						}).then(res => {})
					}

					if (platform != 'ios') {
						that.xuanfuchuang()
					}
				}
			}, 2000)


		},
		onReady() {
			uni.setNavigationBarTitle({
				title: this.$t("设置")
			})
		},
		methods: {
			setPermissions_action() {
				// #ifdef APP-PLUS
				console.log('系统通知权限')
				setPermissions();
				// #endif
			},
			//语音切换
			langChange(lang) {
				uni.setStorageSync("lang", lang)
				this.$i18n.locale = lang
				this.lang = lang
				getApp().globalData.lang = lang
				this.$store.commit("setTabBar", this);
			},

			//登出
			async logOut() {

				const agreeApp = uni.getStorageSync("agreeApp")
				uni.clearStorage();
				uni.clearStorageSync();
				if (agreeApp) uni.setStorageSync("agreeApp", agreeApp)

				// #ifndef MP-WEIXIN

				let chat = TencentCloudChat.create({
					SDKAppID: 1400818966
				});


				await chat.logout();

				try {
					// 移除消息监听
					// await chat.logout();
					// location.reload();
					// await logout();

					const SDKAppID = 1400818966; // 您的 SDKAppID
					const appKey = '5pHuHI6yPdrnl481F7OfIHzWi8Uop6qMYgfDOvZ4XTeSRFtcFVUm0B4rIEusroyo'; // 客户端密钥
					Push.registerPush(SDKAppID, appKey, (data) => {
						console.log('registerPush ok', data);
						Push.getRegistrationID((registrationID) => {
							console.log('getRegistrationID ok', registrationID);
						});
					}, (errCode, errMsg) => {
						console.error('registerPush failed', errCode, errMsg);
					});

					// 监听在线推送 // res 为消息内容
					Push.removePushListener(Push.EVENT.MESSAGE_RECEIVED, (res) => {
						console.log('message received', res);
					});

					// 监听在线推送被撤回 // res 为被撤回的消息 ID
					Push.removePushListener(Push.EVENT.MESSAGE_REVOKED, (res) => {
						console.log('message revoked', res);
					});
					console.log('成功退出登录，已停止接收消息');
				} catch (error) {
					console.error('退出失败', error);
				}
				//let promise1 = chat.logout();
				// promise1.then(function(imResponse) {
				// 	console.log(imResponse.data); // 登出成功
				// }).catch(function(imError) {
				// 	console.warn('logout error:', imError);
				// });
				// #endif

				this.$u.toast(this.$t('操作成功'))
				setTimeout(() => {
					this.$u.route({
						// url: '/pages/tabbar/startPage/language'
						url: '/pages/user/login/login',
					})
				}, 2000)
				return false
			},

			// 关于我们
			link() {
				this.$u.route({
					url: '/pages/user/privacy/privacy',
					params: {
						type: '关于我们'
					}
				})
			},

			//隐私政策
			yinsi() {
				this.$u.api.basic.getContentData({
					type: "隐私政策",
					nowlang: getApp().globalData.lang
				}).then(res => {
					this.xyContent2 = res
				})
				this.showPopup2 = true
			},

			//清除缓存
			clear() {
				uni.clearStorage();
				uni.clearStorageSync();
				setTimeout(() => {
					uni.showToast({
						title: "success",
						icon: "success"
					})
				}, 1000)
			},

			// 检查更新
			inspect() {
				this.show = true
			},

			//注销
			cancel() {
				uni.showModal({
					content: this.$t('确认注销账号吗？注销后不可恢复，请谨慎操作'),
					cancelText: this.$t('否'),
					confirmText: this.$t('是'),
					success: (res) => {
						if (res.confirm) {
							this.logOut()
						} else if (res.cancel) {}
					}
				})
			},

			//用户账号服务协议
			policy() {
				this.$u.route({
					url: '/pages/user/privacy/privacy',
					params: {
						type: 'GLUZ用户账号服务协议'
					}
				})
			},

			//政策隐藏
			guanbi() {
				this.showPopup = false
				this.showPopup2 = false
			},

			//个人资料
			getUserInfo() {
				const that = this
				that.$u.api.user.getUserInfo().then(res => {
					that.is_push = res.is_push
					if (that.is_push == 1) {
						that.isChecked = true
					} else {
						that.isChecked = false
					}
					if (res.is_tj == 1) {
						that.isChecked2 = true
					} else {
						that.isChecked2 = false
					}
				})
			},

			//设置定推开关
			is_push_action() {
				const that = this
				that.$u.api.user.is_push().then(res => {
					that.$u.toast(this.$t('操作成功'))
				})
			},

			//设置推荐开关
			is_tj_action() {
				const that = this
				that.$u.api.user.is_tj().then(res => {
					that.$u.toast(this.$t('操作成功'))
				})
			},

			//跳转官网
			tz() {
				uni.navigateTo({
					url: '/pages/webview/webview?url=https://www.gluz.com.cn'
				})
			},

			//开启麦克风权限
			kaiqi() {

				var that = this
				if (this.platform != 'ios') {
					uni.showModal({
						title: that.$t("该功能将获取以下权限"),
						content: that.$t("麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中"),
						confirmText: that.$t("同意"),
						cancelText: that.$t("算了"),
						success(e) {
							if (e.confirm) {


								var main = plus.android.runtimeMainActivity(); // 获取主Activity
								var Intent = plus.android.importClass('android.content.Intent');
								var Settings = plus.android.importClass('android.provider.Settings');
								var intent = new Intent(Settings.ACTION_SETTINGS);
								main.startActivity(intent);


							}
						}
					})

				} else {
					uni.showModal({
						title: that.$t("该功能将获取以下权限"),
						content: that.$t("麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中"),
						confirmText: that.$t("同意"),
						cancelText: that.$t("算了"),
						success(e) {
							if (e.confirm) {
								var avaudiosession = plus.ios.import("AVAudioSession");
								var avaudio = avaudiosession.sharedInstance();
								console.log(avaudio)
								avaudio.requestRecordPermission(() => {
									console.log('回调完成');
								});


								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
								plus.ios.invoke(app, 'openURL:', setting);
								plus.ios.deleteObject(setting);
								plus.ios.deleteObject(app);

							}
						}
					})
				}
			},

			//安卓麦克风权限
			async requestAndroidPermission(id) {
				var that = this
				var result = await permision.requestAndroidPermission(id)
				console.log(result)
				var strStatus
				if (result == 1) {
					strStatus = "已获得授权"
					that.isChecked3 = true
					that.record_quanxian = "已获得权限"
					uni.setStorageSync('record_permission', 1);
				} else if (result == 0) {
					strStatus = "未获得授权"
					that.isChecked3 = false
					that.record_quanxian = "未获得授权"
					uni.setStorageSync('record_permission', 0);
					// uni.showModal({
					// 	title: that.$t("该功能将获取以下权限"),
					// 	content: that.$t("麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中"),			
					// 	confirmText: that.$t("同意"),
					// 	cancelText: that.$t("算了"),
					// 	success(e) {
					// 		if (e.confirm) {
					// 			var main = plus.android.runtimeMainActivity(); // 获取主Activity
					// 			var Intent = plus.android.importClass('android.content.Intent');
					// 			var Settings = plus.android.importClass('android.provider.Settings');
					// 			var intent = new Intent(Settings.ACTION_SETTINGS);
					// 			main.startActivity(intent);
					// 		}
					// 	}
					// })	
				} else {
					strStatus = "被永久拒绝权限"
					that.isChecked3 = true
					that.record_quanxian = "被永久拒绝权限"
					uni.setStorageSync('record_permission', 1);
				}

			},


			//ios麦克风权限
			async requestIosPermission2(id) {
				var that = this
				var result = await permision.judgeIosPermission(id)
				console.log(result)
				if (result == false) {
					that.isChecked3 = false
					that.record_quanxian = "未获得授权"
					uni.setStorageSync('record_permission', 0);
					// uni.showModal({
					// 	title: that.$t("该功能将获取以下权限"),
					// 	content: that.$t("麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中"),			
					// 	confirmText: that.$t("同意"),
					// 	cancelText: that.$t("算了"),
					// 	success(e) {
					// 		if (e.confirm) {
					// 			var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					// 			var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
					// 			plus.ios.invoke(app, 'openURL:', setting);
					// 			plus.ios.deleteObject(setting);
					// 			plus.ios.deleteObject(app);
					// 		}
					// 	}
					// })	
				} else {
					that.isChecked3 = true
					that.record_quanxian = "已获得权限"
					uni.setStorageSync('record_permission', 1);
				}
			},

			//悬浮窗检测
			xuanfuchuang() {
				let main = plus.android.runtimeMainActivity();
				let pkName = main.getPackageName()
				let Settings = plus.android.importClass('android.provider.Settings')
				let Uri = plus.android.importClass('android.net.Uri')
				let Intent = plus.android.importClass('android.content.Intent')
				let intent = new Intent(
					'android.settings.action.MANAGE_OVERLAY_PERMISSION',
					Uri.parse('package:' + pkName)
				)
				// 检测悬浮窗  
				if (!Settings.canDrawOverlays(main)) {
					this.isChecked4 = false
					uni.setStorageSync('xuanfuchuang_permission', 0);

					// uni.showModal({
					// 	title: '温馨提示',
					// 	content: '请先打开悬浮窗权限',
					// 	showCancel: true,
					// 	success: function(res) {
					// 		if (res.confirm) {
					// 			main.startActivityForResult(intent, 5004) // 转跳到悬浮窗设置  
					// 		}
					// 	}
					// })
				} else {
					this.isChecked4 = true
					uni.setStorageSync('xuanfuchuang_permission', 1);
				}
			},

			//悬浮窗检测
			xuanfuchuang_action() {
				let main = plus.android.runtimeMainActivity();
				let pkName = main.getPackageName()
				let Settings = plus.android.importClass('android.provider.Settings')
				let Uri = plus.android.importClass('android.net.Uri')
				let Intent = plus.android.importClass('android.content.Intent')
				let intent = new Intent(
					'android.settings.action.MANAGE_OVERLAY_PERMISSION',
					Uri.parse('package:' + pkName)
				)

				main.startActivityForResult(intent, 5004) // 转跳到悬浮窗设置  
			},
		}
	}
</script>

<style lang="scss" scoped>
	p {
		width: 95% !important;
	}

	.u-page {
		height: 100%;
		padding: 0rpx 47rpx 0 47rpx;

		.about-me {
			// height: 178rpx;
			height: 238rpx;
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			margin-bottom: 163rpx;
		}

		.sect:nth-child(n+2) {
			width: 100%;
			margin-top: 41rpx;
		}
	}

	.mask {
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		align-items: center;
		width: 335rpx;
		height: 286rpx;
		background: #FFFFFF;
		border-radius: 24rpx;
		margin: 60% auto;

		image {
			width: 113rpx;
			height: 95rpx;
		}

		text {
			width: 122rpx;
			height: 35rpx;
			font-size: 24rpx;

			font-weight: 500;
			color: #2D2D2D;
			line-height: 35rpx;
		}
	}


	.xy-popup {
		margin-top: 20px;
		margin-bottom: 20px;
		width: 94%;
		padding: 40rpx 40rpx 40rpx 40rpx;
	}

	.xy-popup-title {
		color: #DE2D11;
		text-align: center;
		font-weight: 500;
	}

	.sect {
		margin: 60rpx 0;
	}

	.logout {
		width: 100%;
		height: 100rpx;
		border-radius: 16rpx;
		background: #3D3D3D;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.langlist {
		display: flex;
		flex-shrink: 0;
		margin-left: 24rpx;

		.item {
			width: 116rpx;
			height: 48rpx;
			border-radius: 16rpx;
			opacity: 1;
			background: #FFFFFF;
			box-sizing: border-box;
			border: 1rpx solid #A4A4A4;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 16rpx;
		}

		.active {
			width: 116rpx;
			height: 48rpx;
			border-radius: 16rpx;
			opacity: 1;
			background: linear-gradient(112deg, #D0EE8B 0%, #E8F6D3 100%);
			box-sizing: border-box;
			border: 2rpx solid #000000;
		}
	}
</style>